import { defineStore } from 'pinia';
import { SysNotificationApi } from '/@/views/_admin/sysnotification/api/index';
import { ElNotification, ElMessage } from 'element-plus';
import { Bell } from '@element-plus/icons-vue';
import { h } from 'vue';
import { Local, Session } from '/@/utils/storage';
import { useUserInfo } from '/@/stores/userInfo';
import type { ISysNotificationView } from '/@/views/_admin/sysnotification/api/interface';
import other from '/@/utils/other';
import NotificationDetail from '/@/components/notificationDetail/index.vue';

// ============ 类型定义 ============
interface NotificationItem extends ISysNotificationView {
  PcRoute?: string;
}

interface NotificationState {
  notifications: NotificationItem[];
  unreadCount: number;
  loading: boolean;
  lastCheckTime: number;
  checkInterval: NodeJS.Timeout | null;
  refreshInterval: NodeJS.Timeout | null;
  errorCount: number;
  maxRetries: number;
  isInitialized: boolean;
  lastNotificationId: string | null;
  initRetryCount: number;
  initRetryTimer: NodeJS.Timeout | null;
}

interface NotificationConfig {
  title: string;
  message: string;
  icon: any;
  duration: number;
  position: 'top-right';
  showClose: boolean;
  customClass: string;
  onClick: () => void;
}

type PriorityLevel = '低' | '普通' | '高' | '紧急';
type NotificationType = 'URGENT' | 'NORMAL';

// ============ 配置常量 ============
const CONFIG = {
  CHECK_INTERVAL: 10000, // 10秒检查一次新消息
  REFRESH_INTERVAL: 60000, // 60秒刷新全部数据
  MAX_RETRIES: 3,
  MAX_NOTIFICATIONS: 100, // 最大通知数量
  NOTIFICATION_DURATION: {
    URGENT: 6000, // 紧急通知持续时间
    NORMAL: 4500, // 普通通知持续时间
  },
  INIT_RETRY_DELAY: 500, // 初始化重试延迟时间
  PRIORITY_LEVELS: {
    URGENT: ['紧急', '高'] as PriorityLevel[],
    NORMAL: ['普通', '低'] as PriorityLevel[],
  },
  PRIORITY_COLORS: {
    URGENT: '#f56c6c',
    HIGH: '#e6a23c',
    NORMAL: '#909399',
    LOW: '#67c23a',
    DEFAULT: '#409eff',
  },
  TEXT_LIMITS: {
    TITLE: 50,
    CONTENT: 80,
  },
  ERROR_CODES: [401, 403],
  DEBOUNCE_DELAY: 300,
  // 时间范围配置
  TIME_RANGES: {
    SEARCH_DAYS: 7, // 查询最近7天的消息
    NOTIFICATION_HOURS: 0.5, // 只显示最近30分钟内的新消息通知
  },
} as const;

// 通知类型配置
const NOTIFICATION_TYPES: Record<NotificationType, { duration: number; title: string; message: string }> = {
  URGENT: {
    duration: CONFIG.NOTIFICATION_DURATION.URGENT,
    title: '紧急通知',
    message: '您有一条紧急的系统通知',
  },
  NORMAL: {
    duration: CONFIG.NOTIFICATION_DURATION.NORMAL,
    title: '新通知',
    message: '您有一条新的系统通知',
  },
} as const;

// ============ 工具类 ============
class NotificationUtils {
  static truncateText(text: string, maxLength: number = 100): string {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  }

  static formatTime(time: Date | string): string {
    if (!time) return '';

    const date = new Date(time);
    const now = new Date();
    const diff = now.getTime() - date.getTime();

    if (diff < 60000) return '刚刚';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
    if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`;

    return date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  }

  static getPriorityColor(priority: string): string {
    const priorityMap: Record<string, string> = {
      '紧急': CONFIG.PRIORITY_COLORS.URGENT,
      '高': CONFIG.PRIORITY_COLORS.HIGH,
      '普通': CONFIG.PRIORITY_COLORS.NORMAL,
      '低': CONFIG.PRIORITY_COLORS.LOW,
    };
    return priorityMap[priority] || CONFIG.PRIORITY_COLORS.DEFAULT;
  }

  static sortNotifications(notifications: NotificationItem[]): NotificationItem[] {
    return [...notifications].sort((a, b) => {
      // 置顶优先
      if (a.IsTop && !b.IsTop) return -1;
      if (!a.IsTop && b.IsTop) return 1;
      // 按时间排序
      return new Date(b.SendTime).getTime() - new Date(a.SendTime).getTime();
    });
  }

  static groupMessagesByPriority(messages: NotificationItem[]) {
    return {
      urgent: messages.filter(msg =>
        CONFIG.PRIORITY_LEVELS.URGENT.includes(msg.Priority as PriorityLevel)
      ),
      normal: messages.filter(msg =>
        CONFIG.PRIORITY_LEVELS.NORMAL.includes(msg.Priority as PriorityLevel)
      ),
    };
  }

  static debounce<T extends (...args: any[]) => any>(
    func: T,
    delay: number
  ): (...args: Parameters<T>) => void {
    let timeoutId: NodeJS.Timeout;
    return (...args: Parameters<T>) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func(...args), delay);
    };
  }
}

// ============ 性能监控类 ============
class PerformanceMonitor {
  private metrics: Array<{
    loadTime: number;
    memoryUsage: number;
    notificationCount: number;
    errorCount: number;
    lastCheckTime: number;
    averageResponseTime: number;
  }> = [];

  private errorCount = 0;
  private totalLoadTime = 0;
  private loadCount = 0;
  private readonly MAX_METRICS = 100;

  recordLoadTime(loadTime: number): void {
    this.totalLoadTime += loadTime;
    this.loadCount++;
  }

  recordError(): void {
    this.errorCount++;
  }

  recordNotificationCount(count: number): void {
    const metrics = {
      loadTime: this.getAverageLoadTime(),
      memoryUsage: this.getMemoryUsage(),
      notificationCount: count,
      errorCount: this.errorCount,
      lastCheckTime: Date.now(),
      averageResponseTime: this.getAverageLoadTime(),
    };

    this.metrics.push(metrics);
    if (this.metrics.length > this.MAX_METRICS) {
      this.metrics.shift();
    }
  }

  private getAverageLoadTime(): number {
    return this.loadCount > 0 ? this.totalLoadTime / this.loadCount : 0;
  }

  private getMemoryUsage(): number {
    if ('memory' in performance) {
      return (performance as any).memory.usedJSHeapSize / 1024 / 1024;
    }
    return 0;
  }

  getSystemHealth() {
    const currentMetrics = this.metrics[this.metrics.length - 1] || {
      loadTime: 0,
      memoryUsage: 0,
      notificationCount: 0,
      errorCount: 0,
      lastCheckTime: Date.now(),
      averageResponseTime: 0,
    };

    let status: 'healthy' | 'warning' | 'critical' = 'healthy';
    let message = '系统运行正常';

    if (currentMetrics.errorCount > 10) {
      status = 'critical';
      message = '错误率过高';
    } else if (currentMetrics.errorCount > 5) {
      status = 'warning';
      message = '错误率较高';
    }

    if (currentMetrics.averageResponseTime > 5000) {
      status = status === 'critical' ? 'critical' : 'warning';
      message = '响应时间过长';
    }

    return { status, message, metrics: currentMetrics };
  }

  reset(): void {
    this.metrics = [];
    this.errorCount = 0;
    this.totalLoadTime = 0;
    this.loadCount = 0;
  }
}

// ============ API服务类 ============
class NotificationApiService {
  private api = SysNotificationApi();

  async searchNotifications(params = {}): Promise<{ data: NotificationItem[], count: number }> {
    const userStore = useUserInfo();

    // 计算最近N天的时间范围
    const now = new Date();
    const daysAgo = new Date(now.getTime() - CONFIG.TIME_RANGES.SEARCH_DAYS * 24 * 60 * 60 * 1000);

    const searchParams = {
      Page: 1,
      Limit: CONFIG.MAX_NOTIFICATIONS,
      Status: '未读',
      ITCode: userStore.userInfos.itCode,
      Receiver: userStore.userInfos.itCode,
      // 尝试多种时间参数名称，适配不同的后端API
      SendTimeStart: daysAgo.toISOString(),
      SendTimeEnd: now.toISOString(),
      StartTime: daysAgo.toISOString(),
      EndTime: now.toISOString(),
      TimeStart: daysAgo.toISOString(),
      TimeEnd: now.toISOString(),
      ...params,
    };



    const response = await this.api.search(searchParams);

    // 返回数据和总数
    return {
      data: (response as any).Data || [],
      count: (response as any).Count || 0
    };
  }

  async getNotificationDetail(id: string): Promise<any> {
    return await this.api.get(id);
  }

  async markAsRead(notification: NotificationItem): Promise<void> {
    await this.api.edit({
      Entity: {
        ...notification,
        Status: '已读',
        ReadTime: new Date()
      }
    });
  }

  async markAllAsRead(): Promise<void> {
    await this.api.markAllAsRead();
  }


}

// ============ 通知管理器类 ============
class NotificationManager {
  private apiService = new NotificationApiService();

  createNotificationConfig(
    type: NotificationType,
    message: NotificationItem,
    count: number,
    onClickHandler: (message: NotificationItem, isSingle: boolean) => void
  ): NotificationConfig {
    const config = NOTIFICATION_TYPES[type];
    const isSingle = count === 1;

    // 只显示单条消息的详细信息，不显示汇总
    const title = message.Title || config.title;
    const content = message.Content || config.message;

    const iconColor = NotificationUtils.getPriorityColor(message.Priority);

    return {
      title: NotificationUtils.truncateText(title || '', CONFIG.TEXT_LIMITS.TITLE),
      message: NotificationUtils.truncateText(content || '', CONFIG.TEXT_LIMITS.CONTENT),
      icon: h(Bell, {
        style: {
          color: iconColor,
          fontSize: '18px'
        }
      }),
      duration: config.duration,
      position: 'top-right' as const,
      showClose: true,
      customClass: 'custom-notification',
      onClick: () => onClickHandler(message, isSingle),
    };
  }

  async showNotificationDetail(message: NotificationItem): Promise<void> {
    try {
      if (!message.ID) {
        ElMessage.error('通知ID不存在');
        return;
      }

      const detailData = await this.apiService.getNotificationDetail(message.ID);

      // 使用 other.openDialog 打开通知详情组件
      other.openDialog(
        '通知详情',
        NotificationDetail,
        detailData,
        () => {
          // 回调函数，用于刷新通知列表
        },
        'min(880px, 92vw)'
      );
    } catch (error) {
      console.error('查询通知详情失败:', error);
      ElMessage.error('查询通知详情失败，请稍后重试');
    }
  }

  showNotifications(newMessages: NotificationItem[], onClickHandler: (message: NotificationItem, isSingle: boolean) => void): void {
    // 为每条新消息单独显示通知，而不是汇总显示
    newMessages.forEach((message, index) => {
      // 添加延迟，避免通知重叠
      setTimeout(() => {
        const config = this.createNotificationConfig(
          CONFIG.PRIORITY_LEVELS.URGENT.includes(message.Priority as PriorityLevel) ? 'URGENT' : 'NORMAL',
          message,
          1,
          onClickHandler
        );
        ElNotification(config);
      }, index * 500); // 每条消息间隔500ms显示
    });
  }
}

// ============ Store定义 ============
const monitor = new PerformanceMonitor();
const notificationManager = new NotificationManager();
const apiService = new NotificationApiService();

export const useNotificationStore = defineStore('notification', {
  state: (): NotificationState => ({
    notifications: [],
    unreadCount: 0,
    loading: false,
    lastCheckTime: 0,
    checkInterval: null,
    refreshInterval: null,
    errorCount: 0,
    maxRetries: CONFIG.MAX_RETRIES,
    isInitialized: false,
    lastNotificationId: null,
    initRetryCount: 0,
    initRetryTimer: null,
  }),

  getters: {
    getUnreadCount: (state) => state.unreadCount,
    getNotifications: (state) => state.notifications,
    getUnreadNotifications: (state) => state.notifications.filter(n => n.Status === '未读'),
    getReadNotifications: (state) => state.notifications.filter(n => n.Status === '已读'),
    isSystemInitialized: (state) => state.isInitialized,
    isLoading: (state) => state.loading,
  },

  actions: {
    // ========== 认证相关 ==========
    isUserLoggedIn(): boolean {
      const token = Local.get('token') || Session.get('token');
      return !!token;
    },

    checkLoginState(): boolean {
      if (!this.isUserLoggedIn()) {
        this.stopAllTimers();
        this.resetState();
        return false;
      }
      return true;
    },

    // ========== 状态管理 ==========
    resetState(): void {
      this.notifications = [];
      this.unreadCount = 0;
      this.isInitialized = false;
      this.lastNotificationId = null;
      this.errorCount = 0;
      this.initRetryCount = 0;

      // 清理重试定时器
      if (this.initRetryTimer) {
        clearTimeout(this.initRetryTimer);
        this.initRetryTimer = null;
      }

      monitor.reset();
    },

    // ========== 初始化 ==========
    async initNotificationSystem(): Promise<void> {
      if (this.isInitialized || !this.checkLoginState()) {
        return;
      }

      try {
        // 确保用户信息已加载
        const userStore = useUserInfo();
        if (!userStore.userInfos.itCode) {
          this.initRetryCount++;
          if (this.initRetryCount > 10) {
            console.warn('用户信息加载超时，停止初始化通知系统');
            return;
          }

          // 清除之前的重试定时器
          if (this.initRetryTimer) {
            clearTimeout(this.initRetryTimer);
          }

          // 设置新的重试定时器
          this.initRetryTimer = setTimeout(() => {
            this.initNotificationSystem();
          }, CONFIG.INIT_RETRY_DELAY);

          return;
        }

        // 清除重试定时器
        if (this.initRetryTimer) {
          clearTimeout(this.initRetryTimer);
          this.initRetryTimer = null;
        }

        // 清除所有现有的通知弹窗
        this.clearAllNotifications();

        await this.loadNotifications();
        this.startNotificationCheck();
        this.startDataRefresh();
        this.isInitialized = true;
        this.initRetryCount = 0; // 重置重试计数

      } catch (error) {
        console.error('通知系统初始化失败:', error);
        this.isInitialized = false;
        throw error;
      }
    },

    // 清除所有通知弹窗
    clearAllNotifications(): void {
      // 关闭所有Element Plus通知
      const notifications = document.querySelectorAll('.el-notification');
      notifications.forEach(notification => {
        const closeBtn = notification.querySelector('.el-notification__closeBtn');
        if (closeBtn) {
          (closeBtn as HTMLElement).click();
        }
      });
    },

    // ========== 数据加载 ==========
    async loadNotifications(): Promise<void> {
      if (this.loading || !this.checkLoginState()) {
        return;
      }

      const startTime = Date.now();

      try {
        this.loading = true;
        const result = await apiService.searchNotifications();
        let newNotifications = NotificationUtils.sortNotifications(result.data);

        // 如果后端不支持时间过滤，在客户端进行过滤
        if (newNotifications.length > 0) {
          const now = new Date();
          const daysAgo = new Date(now.getTime() - CONFIG.TIME_RANGES.SEARCH_DAYS * 24 * 60 * 60 * 1000);

          const filteredNotifications = newNotifications.filter(item =>
            new Date(item.SendTime) >= daysAgo
          );

          if (filteredNotifications.length !== newNotifications.length) {

            newNotifications = filteredNotifications;
          }
        }

        // 检测新消息
        this.detectNewNotifications(newNotifications);

        // 更新状态 - 使用过滤后的数据
        this.notifications = newNotifications;
        this.unreadCount = newNotifications.length; // 使用过滤后的数量
        this.lastCheckTime = Date.now();
        this.errorCount = 0;

        // 记录性能指标
        const loadTime = Date.now() - startTime;
        monitor.recordLoadTime(loadTime);
        monitor.recordNotificationCount(this.notifications.length);



      } catch (error) {
        this.handleLoadError(error);
        throw error;
      } finally {
        this.loading = false;
      }
    },





    // ========== 错误处理 ==========
    handleLoadError(error: any): void {
      this.errorCount++;
      monitor.recordError();

      console.error('加载通知失败:', error);

      // 达到最大重试次数时停止定时器
      if (this.errorCount >= this.maxRetries) {
        console.warn('通知系统错误次数过多，停止自动刷新');
        this.stopAllTimers();
        return;
      }

      // 认证错误时停止定时器
      const errorResponse = error as any;
      if (CONFIG.ERROR_CODES.includes(errorResponse?.response?.status)) {
        console.warn('认证失败，停止通知系统');
        this.stopAllTimers();
        return;
      }
    },

    // ========== 新消息检测 ==========
    detectNewNotifications(newNotifications: NotificationItem[]): void {
      // 首次加载时不显示通知
      if (this.notifications.length === 0) {
        this.lastNotificationId = newNotifications[0]?.ID || null;
        return;
      }

      // 获取当前时间，用于过滤最近的消息
      const now = new Date();
      const hoursAgo = new Date(now.getTime() - CONFIG.TIME_RANGES.NOTIFICATION_HOURS * 60 * 60 * 1000);

      // 过滤出真正的新消息：ID不存在且发送时间在最近N小时内
      const newMessages = newNotifications.filter(item => {
        const isNewId = !this.notifications.some(oldItem => oldItem.ID === item.ID);
        const isRecent = new Date(item.SendTime) >= hoursAgo;
        const isUnread = item.Status === '未读';
        return isNewId && isRecent && isUnread;
      });

      if (newMessages.length > 0) {
        this.showNotificationForNewMessages(newMessages);
        this.lastNotificationId = newMessages[0].ID || null;
      }
    },

    showNotificationForNewMessages(newMessages: NotificationItem[]): void {
      notificationManager.showNotifications(newMessages, this.handleNotificationClick.bind(this));
    },

    async handleNotificationClick(message: NotificationItem, isSingle: boolean): Promise<void> {
      await notificationManager.showNotificationDetail(message);
      // 点击后刷新通知列表
      this.loadNotifications();
    },

    // ========== 定时器管理 ==========
    startNotificationCheck(): void {
      this.stopCheckTimer();

      const debouncedLoad = NotificationUtils.debounce(async () => {
        if (this.checkLoginState() && !this.loading && this.errorCount < this.maxRetries) {
          try {
            await this.loadNotifications();
          } catch (error) {
            // 静默处理错误，错误已在loadNotifications中处理
          }
        }
      }, CONFIG.DEBOUNCE_DELAY);

      this.checkInterval = setInterval(debouncedLoad, CONFIG.CHECK_INTERVAL);
    },

    startDataRefresh(): void {
      this.stopRefreshTimer();

      this.refreshInterval = setInterval(async () => {
        if (this.checkLoginState() && !this.loading && this.errorCount < this.maxRetries) {
          try {
            await this.loadNotifications();
          } catch (error) {
            // 静默处理错误
          }
        }
      }, CONFIG.REFRESH_INTERVAL);
    },

    stopCheckTimer(): void {
      if (this.checkInterval) {
        clearInterval(this.checkInterval);
        this.checkInterval = null;
      }
    },

    stopRefreshTimer(): void {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
    },

    stopAllTimers(): void {
      this.stopCheckTimer();
      this.stopRefreshTimer();
    },

    // ========== 消息操作 ==========
    async markAsRead(notificationId: string): Promise<void> {
      try {
        const notification = this.notifications.find(n => n.ID === notificationId);
        if (!notification) {
          throw new Error('通知不存在');
        }

        await apiService.markAsRead(notification);
        await this.loadNotifications();
      } catch (error) {
        console.error('标记已读失败:', error);
        throw error;
      }
    },

    async markAllAsRead(): Promise<void> {
      try {
        await apiService.markAllAsRead();
        await this.loadNotifications();
      } catch (error) {
        console.error('全部标记已读失败:', error);
        throw error;
      }
    },

    // ========== 生命周期管理 ==========
    cleanup(): void {
      this.stopAllTimers();
      this.resetState();
    },

    async restartNotificationSystem(): Promise<void> {
      this.cleanup();
      await this.initNotificationSystem();
    },

    // 手动触发初始化（用于调试或特殊情况）
    async forceInit(): Promise<void> {
      this.resetState();
      await this.initNotificationSystem();
    },

    // ========== 事件处理 ==========
    onLoginStateChange(): void {
      if (this.isUserLoggedIn()) {
        this.restartNotificationSystem();
      } else {
        this.checkLoginState();
      }
    },

    onUserLogin(): void {
      this.restartNotificationSystem();
    },

    onUserLogout(): void {
      this.cleanup();
    },



    // ========== 系统监控 ==========
    getSystemStatus(): object {
      const health = monitor.getSystemHealth();

      // 统计最近24小时的消息
      const now = new Date();
      const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
      const recentNotifications = this.notifications.filter(n =>
        new Date(n.SendTime) >= oneDayAgo
      );

      return {
        isInitialized: this.isInitialized,
        unreadCount: this.unreadCount,
        totalNotifications: this.notifications.length,
        recentNotificationsCount: recentNotifications.length,
        errorCount: this.errorCount,
        lastCheckTime: this.lastCheckTime,
        hasTimers: !!(this.checkInterval || this.refreshInterval),
        isLoggedIn: this.isUserLoggedIn(),
        config: {
          checkInterval: CONFIG.CHECK_INTERVAL,
          refreshInterval: CONFIG.REFRESH_INTERVAL,
          maxRetries: CONFIG.MAX_RETRIES,
          timeRanges: CONFIG.TIME_RANGES,
        },
        performance: {
          health: health.status,
          message: health.message,
          metrics: health.metrics,
        },
        recentMessages: {
          last24Hours: recentNotifications.length,
          oldestMessage: this.notifications.length > 0 ?
            NotificationUtils.formatTime(this.notifications[this.notifications.length - 1].SendTime) : '无',
          newestMessage: this.notifications.length > 0 ?
            NotificationUtils.formatTime(this.notifications[0].SendTime) : '无',
        },
      };
    },

    getPerformanceReport(): string {
      const health = monitor.getSystemHealth();
      return `系统状态: ${health.status}\n状态信息: ${health.message}`;
    },

    getSystemHealth(): any {
      return monitor.getSystemHealth();
    },


  },
});

// ============ 导出工具函数 ============
export const notificationUtils = {
  truncateText: NotificationUtils.truncateText,
  formatTime: NotificationUtils.formatTime,
  getPriorityColor: NotificationUtils.getPriorityColor,
  sortNotifications: NotificationUtils.sortNotifications,
  groupMessagesByPriority: NotificationUtils.groupMessagesByPriority,
};

// 导出类型
export type { NotificationItem, NotificationState, PriorityLevel, NotificationType };